// Copyright (c) 2025, Your Company Pvt. Ltd.
// License: GNU General Public License v3. See license.txt

frappe.query_reports["consumption_7days"] = {
    filters: [
        {
            fieldname: "company",
            label: __("公司"),
            fieldtype: "Link",
            options: "Company",
            default: frappe.defaults.get_user_default("Company"),
            reqd: 1,
            description: __("选择统计的公司")
        },
        {
            fieldname: "item_code",
            label: __("物料"),
            fieldtype: "Link",
            options: "Item",
            description: __("可选：筛选特定物料")
        },
        {
            fieldname: "item_group",
            label: __("物料组"),
            fieldtype: "Link",
            options: "Item Group",
            description: __("可选：筛选特定物料组")
        },
        {
            fieldname: "warehouse",
            label: __("仓库"),
            fieldtype: "Link",
            options: "Warehouse",
            description: __("可选：筛选特定仓库的使用量")
        },
        {
            fieldname: "show_disabled_items",
            label: __("显示禁用物料"),
            fieldtype: "Check",
            default: 0,
            description: __("默认不显示已禁用的物料")
        }
    ],
    onload: function(report) {
        report.refresh(); // 初始加载刷新
        // 筛选器变化时自动刷新
        report.$wrapper.on("change", "[data-fieldname]", function() {
            report.refresh();
        });
    },
    formatter: function(value, row, column, data, default_formatter) {
        let formatted_value = default_formatter(value, row, column, data);
        
        // 获取今天的日号（两位数，与报表列名匹配，如“27”）
        const today = new Date();
        const todayDay = String(today.getDate()).padStart(2, '0'); // 确保是两位数（如5→"05"）
        
        // 仅对“今天的列”生效（字段名等于今天的日号）
        if (column.fieldname === todayDay) {
            const todayUsage = parseFloat(data[todayDay] || 0); // 今天的用量
            const total7days = parseFloat(data.total_7days_usage || 0); // 7天总用量
            const avg7days = total7days > 0 ? total7days / 7 : 0; // 7天平均用量
            
            let ratio = 0;
            if (avg7days > 0) {
                ratio = todayUsage / avg7days; // 今天用量 / 平均用量
            } else if (todayUsage > 0) {
                ratio = Infinity; // 平均为0但今天有用量，视为远超100%
            }
            
            // 优化样式：确保数字可见，仅背景色变化
            if (ratio > 1) {
                formatted_value = `<span style="background-color: #ffcccc; color: black; display: inline-block; width: 100%; padding: 2px;">${formatted_value}</span>`;
            } else if (ratio > 0.5) {
                formatted_value = `<span style="background-color: #fff3cd; color: black; display: inline-block; width: 100%; padding: 2px;">${formatted_value}</span>`;
            }
        }
        
        return formatted_value;
    }
};